<?php
namespace App\Http\Controllers\Laifei\Explore;

use App\Http\Controllers\Controller;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiExploreStoreController extends Controller
{

    public function index()
    {
        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 20;
        $pageNo = $all['pageNo'] ?? 1;

        try{
            $where = function ($query) use ($all) {
                if(isset($all['shop_name'])){
                    $query->where('shop.shop_name','like','%'.$all['shop_name'].'%');
                }
                if(isset($all['channel_id']) && count($all['channel_id'])){
                    $query->whereIn('eo.channel_id',$all['channel_id']);
                }
                if(isset($all['status']) && count($all['status'])){
                    $query->whereIn('eo.status',$all['status']);
                }
                if(isset($all['contact_phone'])){
                    $query->where('shop.contact_phone','=',$all['contact_phone']);
                }
            };

            $total = DB::table('explore_order as eo')
                ->leftJoin('shop','eo.shop_id','=','shop.shop_id')
                ->where($where)
                ->count();

            $info = DB::table('explore_order as eo')
                ->leftJoin('shop','eo.shop_id','=','shop.shop_id')
                ->leftJoin('dict_area as da','shop.district','=','da.id')
                ->leftJoin('explore_channel as ec','eo.channel_id','=','ec.channel_id')
                ->where($where)
                ->select('eo.eo_id','eo.shop_id','eo.channel_id','eo.start_date','eo.end_date','eo.total_num','eo.remaining_num','eo.distribution_num',
                    'eo.pending_num','eo.success_num','eo.failed_num','eo.status','eo.created_at','shop.shop_name',
                    'shop.contact_man','shop.contact_phone','shop.province','shop.city','shop.district','shop.address','da.short_name',
                    'ec.channel_name')
                ->orderByDesc('eo.eo_id')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->get()
                ->map(function($item){
                    $item->status_name = Data::$exploreOrderStatus[$item->status];
                    return $item;
                })
                ->toArray();

            return $this->setReturnJson(0,'success',['total'=>$total,'info'=>$info]);
        }catch (\Exception $e){
            Log::error(LaifeiExploreStoreController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'查询失败',['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

    }

}
